# coding:utf-8
class Admin::TerminalGroupsController < AdminController
	
  respond_to :html, :json

  before_filter :check_access
  set_tab :terminals
  before_filter :setup, only: [:index]

  def index
    @terminal_groups = TerminalGroup
    if params[:city_id].present?
      @city = City.find_by_id(params[:city_id])
      @terminal_groups = @terminal_groups.where(city_id: params[:city_id])
      eval %{set_tab :city_#{@city.id}, :sub_nav}
      @ways += [@city.province.name,@city.name,"设备管理"]
    else
      set_tab :terminal_groups, :sub_nav
    end
    @terminal_groups = @terminal_groups.order('id ASC')
	end

  def new
    @terminal_group = TerminalGroup.new(:city_id => params[:city_id])
    @terminals = []
  end

  def edit
    @terminal_group = TerminalGroup.find params[:id]
    @terminals = Terminal.where(terminal_group_id: @terminal_group.id)
  end

  def create
    terminal_ids = params[:terminal_group].delete(:terminal_ids)
    @terminal_group = TerminalGroup.new(params[:terminal_group])
    if @terminal_group.save
      Terminal.where(id: terminal_ids).each do |t|
        t.terminal_group_id = @terminal_group.id
        t.save!
      end
    else
      render :action => :new 
    end
  end

  def update
    terminal_ids = params[:terminal_group].delete(:terminal_ids)
    @terminal_group = TerminalGroup.find params[:id]
    if @terminal_group.update_attributes(params[:terminal_group])
      # set null for pre-group
      Terminal.where(terminal_group_id: @terminal_group.id).each do |t|
        t.terminal_group_id = nil
        t.save!
      end

      # set the new group
      Terminal.where(id: terminal_ids).each do |t|
        t.terminal_group_id = @terminal_group.id
        t.save!
      end
    else
      render :action => :edit 
    end
  end

  def destroy
    @terminal_group = TerminalGroup.find params[:id]
    @terminal_group.destroy
  end

  private

  def setup
    @ways = ["设备","设备管理"]
    @left_panel = "admin/areas/area_widget"
  end

  def check_access
    if params[:city_id].present?
      @city = City.find_by_id(params[:city_id])
      unless current_admin.can_access?(@city)
        render :file => "public/403.html", :status => 403
      end
    end
  end

end